package com.mdtx.base.filter;

import com.alibaba.fastjson.JSON;
import com.mdtx.base.ResultData;
import com.mdtx.base.SystemErrorCode;
import com.mdtx.base.exception.BaseException;
import com.mdtx.base.security.AccessToken;
import com.mdtx.base.security.cache.LocalTokenCache;
import com.mdtx.base.security.context.AccessTokenContext;
import com.mdtx.base.security.type.AudienceType;
import com.mdtx.base.security.type.SubjectType;
import com.mdtx.utils.LogHelper;
import com.mdtx.utils.StringUtils;
import com.sun.xml.internal.rngom.parse.host.Base;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sun.applet.Main;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截
 *
 * @author zhgz
 * @create 2017-08-27 16:05
 **/
public class LoginHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws BaseException {

        StringBuffer url = request.getRequestURL();
        String path = url.substring( url.lastIndexOf("/"));

        LogHelper.log("...request..url..."+url);

        //过滤非拦截地址
        if(urlFilter(path)){
            //returnData(response);
            return true;
        }else{
            String accessToken = request.getHeader(AccessToken.TOKEN);

            if(StringUtils.isEmpty(accessToken)){
                throw new BaseException(SystemErrorCode.TOKE_INVALID);
            }

            //验证token
            int accessTokenCode = AccessToken.vlidateAccessToken(accessToken);

            if(AccessToken.OVERTIME == accessTokenCode){

                //用户类型
                String aud = AccessToken.pasrseAccessTokenAud(accessToken);

                if(aud.equals(AudienceType.PHONE_USER)){
                    //AccessTokenContext context = LocalTokenCache.getAccessTokenContext();
                    throw new BaseException(SystemErrorCode.TOKE_OVERTIME);
                }else if(aud.equals(AudienceType.PC_USER)){

                }else{
                    throw new BaseException(SystemErrorCode.TOKE_INVALID);
                }


            }

            return true;

        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
       // System.out.println("请求处理之后调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       // System.out.println("请求结束调用");
    }

    /**
     *  拦截后返回前台数据
     * @param response
     */
    private void returnData(HttpServletResponse response){

        ResultData rd = new ResultData();
        rd.setCode(0);
        rd.setMessage("success");
        rd.setData("ssss");
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            LogHelper.info("返回异常",e,LoginHandlerInterceptor.class);
        }
        pw.print(JSON.toJSONString(rd));
        pw.flush();
        pw.close();

    }

    /**
     * 过滤指定的URL
     * @param url
     * @return
     */
    private static boolean urlFilter(String url){

        boolean isOk = false;
        switch (url){
            case "/signIn" :
                isOk = true;
            case "/signUp" :
                isOk = true;
            case "/ui" :
                isOk = true;
            case "/swagger-resources" :
                isOk = true;
            case "/api-docs" :
                isOk = true;
            case "/security" :
                isOk = true;

        }

        return isOk;

    }


}
